package popcorn.ticket.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import popcorn.ticket.dao.UsersMapper;
import popcorn.ticket.service.UsersService;

@Controller
public class LoginController {
	@Autowired
	UsersService usersService;
	@Autowired
	UsersMapper usersmapper;

	Logger logger = Logger.getLogger(LoginController.class);
	// 后台登录方法
	@PostMapping("login")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		// 获得用户名，用户密码，检查用户是否勾选记住密码
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		boolean cksremember = Boolean.parseBoolean(request.getParameter("cksremember"));
		String msg = "请检查用户名/手机号/密码是否正确！";
		// 调用service中的验证帐号密码是否正确，用户帐号是否被禁用
		boolean flag = usersService.login(username, userpwd, session);
		logger.debug("flag:"+flag);
		//获得用户权限
		int power = usersService.info(username);
		logger.debug("power:"+power);
		if (flag && power == 0) {
			// 记住密码
			if (cksremember) {
				Cookie cookie1 = new Cookie("username", username);
				Cookie cookie2 = new Cookie("userpwd", userpwd);
				// 保存时间为7天
				cookie1.setMaxAge(7 * 24 * 60 * 60);
				cookie2.setMaxAge(7 * 24 * 60 * 60);
				// 在webapp文件夹下的所有应用共享cookie
				cookie1.setPath("/");
				cookie2.setPath("/");
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}
			// 转发
			msg = "登录成功";
			ModelAndView mv = new ModelAndView("index");
			mv.addObject("msg", msg);
			return mv;
		}
		ModelAndView mv = new ModelAndView("forward:login.jsp");
		mv.addObject("msg", msg);
		// 传参
		return mv;
	}

}
